package ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * Classe che rappresenta il pannello in cui un utente scrive e manda il proprio messaggio
 * 
 * @author Java e Le Storie Tese
 *
 */

public class WritingPanel extends JPanel implements IWritingPanel {

	private static final long serialVersionUID = 0;

	private BufferedWriter bw;
	
	private Socket socket;
	private String nickName="";
	
	public WritingPanel(Socket s, String nick) {
		super();
		this.socket = s;
		this.nickName = nick;
		
		
		try {
			bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8"));
		} catch (IOException e) {
			System.err.println("Errore nella creazione dell'OutputStream");
		}
		
		try {
			bw.write("+"+nickName+"\n");
			bw.flush();
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		this.add(writingGenerator(nickName,bw,""));
		
		
		
	}

	public JTextField writingGenerator(final String nickName, final BufferedWriter bw, final String id) {
		
		final JTextField writingField=new JTextField(30);
		
		writingField.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					bw.write(id+nickName+" : "+writingField.getText()+"\n");
					bw.flush();
					
				} catch (IOException e) {
					System.err.println("Errore nella scrittura sullo Stream");
				}
				
				writingField.setText("");
			}
		});
		
		return writingField;
		
	}

	public BufferedWriter getBw() {
		return bw;
	}
	
}
